<template>
  <div>
    <el-row>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/home/goods' }">
          商品管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>添加商品</el-breadcrumb-item>
      </el-breadcrumb>
    </el-row>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        center
        :closable="false"
        class="alertSize"
      >
      </el-alert>
      <el-steps align-center :active="stepsActive" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addCommodityList"
        :rules="addCommodityRules"
        ref="ruleForm"
        label-width="100px"
        label-position="top"
        class="demo-ruleForm"
      >
        <el-tabs tab-position="left" :before-leave="leaveTabs">
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addCommodityList.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addCommodityList.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addCommodityList.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addCommodityList.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <div class="block">
                <el-cascader
                  v-model="isCommodityCategoryList"
                  :options="commodityCategoryList"
                  :props="isCommodityCategoryProps"
                  @change="handleChange"
                ></el-cascader>
              </div>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-row
              v-for="(item, index) in attributesCategoriesMany"
              :key="index"
            >
              <el-form-item :label="item.attr_name">
                <el-tag
                  v-for="(tag, index) in item.attr_vals"
                  :key="index"
                  closable
                >
                  {{ tag }}
                </el-tag>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-row
              v-for="(item, index) in attributesCategoriesOnly"
              :key="index"
            >
              <el-form-item :label="item.attr_name">
                <el-tag
                  v-for="(tag, index) in item.attr_vals"
                  :key="index"
                  closable
                >
                  {{ tag }}
                </el-tag>
              </el-form-item>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :headers="actionHeader"
              :on-success="uploadSuccess"
              :on-remove="removeUploadSuccess"
              :on-preview="handlePictureCardPreview"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="isUploadDialogVisible" width="50%">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor
              ref="myQuillEditor"
              v-model="addCommodityList.goods_introduce"
            />
            <el-button
              type="primary"
              round
              class="addButton"
              @click="postAddCommodityList"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 表单绑定内容
      addCommodityList: {
        goods_name: "",
        goods_cat: "",
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        goods_introduce: "",
        pics: [],
        attrs: [],
      },
      //   表单验证规则
      addCommodityRules: {
        goods_name: [
          { required: true, message: "请输入内容", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "价格必须为数值类型", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "重量必须为数值类型", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入内容", trigger: "blur" },
          { type: "number", message: "数量必须为数值类型", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入内容", trigger: "change" },
        ],
      },
      //   表单标签切换验证
      isleaveTabs: false,
      //   表单标签切换对应步骤条
      stepsActive: 0,

      //   表单级联选择框渲染规则
      isCommodityCategoryProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
      },
      //   表单级联选择框内容
      commodityCategoryList: [],

      //   表单级联选择框选中内容
      isCommodityCategoryList: [],
      //   判断获取动态参数还是静态属性
      isCategories: "many",
      //   商品参数或属性
      attributesCategoriesMany: [],
      attributesCategoriesOnly: [],
      // 上传商品页面放大图片
      dialogImageUrl: "",
      isUploadDialogVisible: false,
    };
  },
  methods: {
    //   选中级联选择器赋值
    handleChange() {
      if (this.isCommodityCategoryList.length !== 3) {
        this.isCommodityCategoryList = [];
        return;
      }
      this.addCommodityList.goods_cat = this.isCommodityCategoryList.toString();
    },
    // 请求级联选择器参数
    async getCategory() {
      const { data: res } = await this.$http({
        url: "/categories",
        method: "get",
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.commodityCategoryList = res.data;
    },
    //   表单标签切换验证
    leaveTabs(newvalue, old) {
      if (newvalue !== 0 && old !== undefined) {
        this.isLeave(newvalue);
        return this.isleaveTabs;
      }
    },
    isLeave(newvalue) {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.isleaveTabs = false;
        } else {
          this.isleaveTabs = true;
          this.stepsActive = newvalue - 0;
          if (this.stepsActive == 1) {
            this.switchArguments();
          } else if (this.stepsActive == 2) {
            this.switchAttribute();
          }
        }
      });
    },
    //   请求商品动态静态参数
    async getParamsList() {
      const { data: res } = await this.$http({
        url: `categories/${
          this.isCommodityCategoryList[this.isCommodityCategoryList.length - 1]
        }/attributes`,
        method: "get",
        params: {
          sel: this.isCategories,
        },
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      const result = res.data;
      result.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(",") : [];
      });
      if (this.isCategories == "many") {
        this.attributesCategoriesMany = result;
      } else {
        this.attributesCategoriesOnly = result;
      }
    },
    switchArguments() {
      this.isCategories = "many";
      this.getParamsList();
    },
    switchAttribute() {
      this.isCategories = "only";
      this.getParamsList();
    },
    //上传商品图片成功的回调
    uploadSuccess(val) {
      const value = {
        pic: val.data.tmp_path,
      };
      this.addCommodityList.pics.push(value);
    },
    // 放大商品图片的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.isUploadDialogVisible = true;
    },
    // 删除商品图片的钩子
    removeUploadSuccess(file) {
      console.log(file);
      this.addCommodityList.pics.forEach((item, index) => {
        if (item == file.response.data.tmp_path) {
          this.addCommodityList.pics.splice(index, 1);
        }
      });
    },
    // 提交添加商品表单
    postAddCommodityList() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;

        this.attributesCategoriesMany.forEach((item) => {
          const val = {};
          val.attr_id = item.attr_id;
          val.attr_value = item.attr_value;
          this.addCommodityList.attrs.push(val);
        });
        this.attributesCategoriesOnly.forEach((item) => {
          const val = {};
          val.attr_id = item.attr_id;
          val.attr_value = item.attr_value;
          this.addCommodityList.attrs.push(val);
        });
        const { data: res } = await this.$http({
          url: "goods",
          method: "post",
          data: {
            ...this.addCommodityList,
          },
        });
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$router.push("/home/goods");
        this.$message.success(res.meta.msg);
      });
    },
  },
  computed: {
    actionHeader() {
      return { Authorization: sessionStorage.getItem("token") };
    },
  },
  created() {
    this.getCategory();
  },
};
</script>

<style lang="less" scoped>
.el-alert {
  margin-bottom: 20px;
}
.el-steps {
  margin-bottom: 20px;
}
.alertSize span {
  font-size: 20px !important;
}
.addButton {
  margin-top: 15px;
}
</style>
